package com.jhjx.wx.mp.handler;

import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.jhjx.wx.mp.utils.HttpClientUtils;
import org.springframework.stereotype.Component;

import com.jhjx.wx.mp.builder.TextBuilder;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;

/**
 * 关注公众号事件处理
 */
@Component
public class SubscribeHandler extends AbstractHandler {

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> context, WxMpService weixinService, WxSessionManager sessionManager) throws WxErrorException {

        this.logger.info("新关注用户 OPENID: " + wxMessage.getFromUser());
        // 获取微信用户基本信息
        try {
            WxMpUser userWxInfo = weixinService.getUserService().userInfo(wxMessage.getFromUser(), null);
            if (userWxInfo != null) {
                // 查询当前用户有没有关注过该公众号
                JSONObject object =  HttpClientUtils.httpGet("http://127.0.0.1:8081/api/shop/getShopUserByOpenId?openId="+userWxInfo.getOpenId());
                if (null != object.get("data")) { // 若关注过则更新
                    JSONObject json = new JSONObject();
                    json.put("careFlag","1");
                    json.put("openId",userWxInfo.getOpenId());
                    JSONObject result =  HttpClientUtils.httpPost("http://127.0.0.1:8081/api/shop/updateCareFlagByOpenId",json);
                    if ("-1".equals(result.get("code"))) {
                        this.logger.error("更新关注发生异常！");
                    }
                } else { // 若没有关注过则添加用户到本地数据库
                    JSONObject json = JSONObject.parseObject(userWxInfo.toString());
                    JSONObject result =  HttpClientUtils.httpPost("http://127.0.0.1:8081/api/shop/addCare",json);
                    if ("-1".equals(result.get("code"))) {
                        this.logger.error("用户信息绑定发生异常！");
                    }
                }
            }
        } catch (WxErrorException e) {
            if (e.getError().getErrorCode() == 48001) {
                this.logger.info("该公众号没有获取用户信息权限！");
            }
        }

        WxMpXmlOutMessage responseResult = null;
        try {
            responseResult = this.handleSpecial(wxMessage);
        } catch (Exception e) {
            this.logger.error(e.getMessage(), e);
        }

        if (responseResult != null) {
            return responseResult;
        }

        try {
            return new TextBuilder().build("感谢关注，想要了解更多设备信息，请访问本公司商城地址：[商城正在开发中，敬请期待~]", wxMessage, weixinService);
        } catch (Exception e) {
            this.logger.error(e.getMessage(), e);
        }
        return null;
    }

    /**
     * 处理特殊请求，比如如果是扫码进来的，可以做相应处理
     */
    private WxMpXmlOutMessage handleSpecial(WxMpXmlMessage wxMessage) throws Exception {
        //TODO
        return null;
    }

}
